const fs = require('fs');
const path = require('path');
const https = require('https');
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const logsOutPutMiddleWare = require('./middleWare/logsOutPut.js');
const { Server } = require("socket.io"); 
// 检查并加载 HTTPS 证书
const loadHttpsOptions = () => {
  const certDirPath = path.resolve(__dirname, 'cert');
  const privateKeyPath = path.resolve(certDirPath, 'beloved.ltd.key');
  const certificatePath = path.resolve(certDirPath, 'beloved.ltd_bundle.crt');
  if (fs.existsSync(privateKeyPath) && fs.existsSync(certificatePath)) {
    try {
      const privateKey = fs.readFileSync(privateKeyPath, 'utf-8');
      const certificate = fs.readFileSync(certificatePath, 'utf-8');
      // 如果证书正确加载，返回证书配置
      return {
        key: privateKey,
        cert: certificate,
      };
    } catch (error) {
      console.error('Error reading certificate files:', error);
      return null;
    }
  }
  return null; // 返回 null 如果没有证书文件
};

const app = express();

// 中间件配置
app.all("*", require('./middleWare/cors.js'));
app.use(bodyParser.json());
app.use(logsOutPutMiddleWare);

/* 客户端文章模块 */
app.use(require('./ORM/custom/routes/article/articleRoute.js'));
app.use(require('./ORM/custom/routes/website/websiteRoute.js'));

/* admin 模块 */
app.use(require('./ORM/admin/routes/article.js'));
app.use(require('./ORM/admin/routes/cos.js'));

/* 公共模块 */
app.use(require('./ORM/public/routes/index.js'));

// WebSocket 模块 - 创建 WebSocket 服务器
const createWebSocketServer = (server) => {
  const io = new Server(server, {
    cors: {
      origin: "*",
      methods: ["GET", "POST"],
      credentials: true,
      allowedHeaders: ["Content-Type"],
    },
  });

  io.on("connection", (socket) => {
    console.log('A client connected');
    socket.on("sendMessage", ({ content }) => {
      const OpenAiRequest = require('./api/openAi/index.js');
      OpenAiRequest(socket, content);
    });
    socket.on("disconnect", () => {
      console.log("Client disconnected");
    });
  });
  return io;
};
// 判断是否启动 HTTPS
const httpsOptions = loadHttpsOptions();
if (httpsOptions) {
  // 如果证书存在，启动 HTTPS 服务
  const httpsServer = https.createServer(httpsOptions, app);
  httpsServer.listen(5137, () => {
    console.log('HTTPS Server is running at https://localhost:5137');
  });
  // 创建 WebSocket 服务器
  const io = createWebSocketServer(httpsServer);
} else {
  // 否则，创建 HTTP 服务
  const httpServer = http.createServer(app);
  httpServer.listen(5137, () => {
    console.log('HTTP Server is running at http://localhost:5137');
  });

  // 创建 WebSocket 服务器
  const io = createWebSocketServer(httpServer);
}
